$(function() {
	// code syntax highlight
	SyntaxHighlighter.all();
	
	// auto-tags
    var $nav = $("#tags"),
        $wrapper = $("#wrapper"),
        $h1 = $("#wrapper").find("h1").eq(0),
        $sections = $wrapper.find("section");
    
    var fragment = "";
    $sections.each(function(i, e) {
    	fragment += "<span>" + $(this).find("h2").text() + "</span>";    	
    });     
    $nav.prepend(fragment);
    
    // anchor
    $nav.delegate("span", "click", function() {
        var index = $(this).index(),
            $elem = $sections.eq(index); 

        $("html, body").animate({
            scrollTop: $elem.offset().top
        }, 300, 'swing');
    });
    
    // auto active
    $wrapper.delegate("li:not(.text)", "click", function() {
    	var $this = $(this);
    	if ($this.is(".active")) {
    		//$this.removeClass("active");
    		return;
    	}
    	$this
            .siblings()
                .removeClass("active")
            .end()
            .addClass("active")    		
	    .parents("section")
	    .siblings("section")
    		.find("li").removeClass("active");
    });
    
    // pin  
    var $pin = $nav.find(".pin").eq(0);
    var closePin = function() {	
		var width = $nav.width(); 
		$nav.animate({"left": -width}, 500);
		$wrapper.animate({"margin-left": "20px", "width": "98%"}, 500);
    },
    expandPin = function() {    
		$nav.animate({"left": "10px"}, 500);
		var bodyWidth = $("body").width(); 
		$wrapper.animate({"margin": "0 20px 20px 300px", "width": bodyWidth - 320 + "px"}, 500);
    },
    doPinAction = function() {
    	var pinIt = $pin.is(".active");
    	pinIt ? expandPin() : closePin();
    }
    
    $nav.delegate(".pin", "click", function() {
    	$(this).toggleClass("active");
    	doPinAction();
    });
    
    $nav.delegate(".pin", "mouseenter", function(evt) {
    	if (!$pin.is(".active")) {
    		expandPin();
    	}
    });
    $wrapper.click(function(){
    	if (!$pin.is(".active")) {
    		closePin();
    	}
    });
    
});

















